<?php
/**
 * Created by PhpStorm.
 * User: JX
 * Date: 2017/9/7
 * Time: 17:18
 */

namespace App\Http\Controllers\API\WeChat;


use App\Http\Controllers\Controller;
use App\Models\Student;
use App\Models\TemplateMessage;
use Illuminate\Http\Request;
use EasyWeChat\Foundation\Application;
use Doctrine\Common\Cache\PredisCache;
use Illuminate\Support\Facades\DB;

class TemplateMessageController extends Controller
{
    private $openPlatform = '';

    public function __construct(Application $app)
    {
        $predis = app('redis')->connection()->client();// connection($name), $name 默认为 `default`
        $cacheDriver = new PredisCache($predis);
        $app->cache = $cacheDriver;
        $this->openPlatform = $app->open_platform;
    }

    public function index(Request $request)
    {
        $queryString = $request->get('query', '');
        $models = TemplateMessage::query()
            ->where('name', 'like', '%' . $queryString . '%')->orderBy('id', 'desc')
            ->paginate();
        return $models;
    }

    /**
     * 添加科室
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new TemplateMessage();
        $model->fill($request->all());
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 修改员工
     * @param User $User
     * @param Request $request
     * @return mixed
     */
    public function update($id, Request $request)
    {
      //  dd($request);
        $itemlist = $request->get('itemlist');
        $WeChat = $request->get('WeChat');
        $url = $request->get('url');
        $students = $request->get('user',[]);
        $org = $request->get('org',[]);
        $data = $this->makeData($itemlist);
        $temp = $this->findModel($id);
        if(empty($org)&&empty($students)){
            if ($WeChat && $url){
            foreach ($WeChat as $item) {
                $wechat = DB::table('we_chats')->where(['id' => $item])->first();
                // dd($wechat,$appId);
                $openPlatform = $this->openPlatform;
                $app = $openPlatform->createAuthorizerApplication($wechat->authorizer_appid, $wechat->authorizer_refresh_token);
                $notice = $app->notice;
                $users = DB::table('wechat_users')->select('open_id')->where(['w_id' => $item])->get();
                if ($users) {
                    foreach ($users as $user) {
                        try{
                            $result = $notice->uses($temp->template_id)->withUrl($url)->andData($data)->andReceiver($user->open_id)->send();
                        }catch (\Exception $e){
                            continue;
                        }
                    }
                }
            }
            }else{
                return response('缺少关键数据', 406);
            }
        }else{
            if($org){
                foreach ($org as $item){
                    $orgs = DB::table('organizational_structures')->where('level_tab', 'like','%-'.$item.'-%')->get();
                    if($orgs){
                        foreach ($orgs as $value){

                            $student =  Student::query()
                                ->orWhere('teach_class',$value->jcbid)->orWhere('business_class',$value->jcbid)
                                ->pluck('u_code')->toArray();

                            $students = array_merge($students,$student);
                        }

                    }

                }
            }
            $students = array_unique($students);
            if ($WeChat && $url) {
                foreach ($WeChat as $item) {
                    $wechat = DB::table('we_chats')->where(['id' => $item])->first();
                    $openPlatform = $this->openPlatform;
                    $app = $openPlatform->createAuthorizerApplication($wechat->authorizer_appid, $wechat->authorizer_refresh_token);
                    $notice = $app->notice;
                    $users = DB::table('wechat_users')->select('open_id')->where(['w_id' => $item])->whereIn('student_code', $students)->get();
                    if ($users) {
                        foreach ($users as $user) {
                            try{
                                $result = $notice->uses($temp->template_id)->withUrl($url)->andData($data)->andReceiver($user->open_id)->send();
                            }catch (\Exception $e){
                                continue;
                            }
                        }
                    }
                }
            }else{
                return response('缺少关键数据', 406);
            }
        }

    }

    protected function makeData($itemlist)
    {
        $arr = [];
        if ($itemlist) {
            foreach ($itemlist as $item) {
                $arr[$item['name']] = $item['value'];
            }
        }
        return $arr;

    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $model->delete();
            return ['state' => 'success'];
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show($id)
    {
        return $this->findModel($id);
    }


    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = TemplateMessage::with('items')->findOrFail($id);
        return $model;
    }
}